//
//  RHColorizer.m
//  iLogColor
//
//  Copyright 2009 Reinier Haasjes 
//  
//  This file is covered by the MIT License.
//  See LICENSE for more information.
//

#import "RHColorizer.h"
#import "debug.h"

@implementation RHColorizer
/*
- (id)init
{
	if (self = [super init]) {
		lineCounter = 0;
		return self;
	}else {
		return nil;
	}
}
 */

//- (NSData *)Makeup:(NSString *)plainString
- (NSAttributedString *)Makeup:(NSString *)plainString
{
//	debug_NSLog(@"Makeup: %d: %@", ++lineCounter, plainString);

	NSColor *textColor;
	NSDictionary *strAttributes = [[[NSDictionary alloc] init] autorelease];
	int arrayCounter, i, x;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	BOOL match;
	
	// Initilize rtfString
	NSMutableAttributedString *rtfString=[[[NSMutableAttributedString alloc] initWithString:plainString] autorelease];
	
	// Get range
	NSRange fullRange=NSMakeRange(0, [rtfString length]);
	
	// Ignore
	NSArray *ignoreArray = [[defaults stringForKey:@"ignoreText"] componentsSeparatedByString:@"\n"];
	arrayCounter = [ignoreArray count];
	for (i=0; i < arrayCounter; i++)
	{
		if ([plainString rangeOfString:[ignoreArray objectAtIndex:i] options:NSCaseInsensitiveSearch].location != NSNotFound)
		{
//			debug_NSLog(@"Ignore: %@", plainString);
			return nil;
		}
	}
		
	 // Initialize match
	match = NO;
	
	// Normal
	NSArray *normalArray = [[defaults stringForKey:@"normalText"] componentsSeparatedByString:@"\n"];
	arrayCounter = [normalArray count];
	for (i=0; i < arrayCounter; i++)
	{
		if ([plainString rangeOfString:[normalArray objectAtIndex:i] options:NSCaseInsensitiveSearch].location != NSNotFound)
		{
			textColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:[defaults dataForKey:@"foregroundColor"]];
			match = YES;
		}
	}

	 // Colors
	if (!match)
	{
		for (x=1; x <= 6 && !match; x++)
		{
			NSArray *colorArray = [[defaults stringForKey:[NSString stringWithFormat:@"text%i", x]] componentsSeparatedByString:@"\n"];
			arrayCounter = [colorArray count];
			for (i=0; i < arrayCounter; i++)
			{
				if ([plainString rangeOfString:[colorArray objectAtIndex:i] options:NSCaseInsensitiveSearch].location != NSNotFound)
				{
					textColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:[defaults dataForKey:[NSString stringWithFormat:@"color%i", x]]];
					match = YES;
				}			
			}
		}
	}
	
	 // Determine default color
	if (!match)
		textColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:[defaults dataForKey:@"foregroundColor"]];

	// Colorize string
	[rtfString beginEditing];
	[rtfString addAttribute:NSFontAttributeName 
					  value:[NSFont fontWithName:@"Lucida Grande" size:[defaults integerForKey:@"fontSize"]]
					  range:fullRange];
	[rtfString addAttribute:NSForegroundColorAttributeName
					  value:textColor
					  range:fullRange];
	[rtfString endEditing];

//	return [rtfString RTFFromRange:fullRange documentAttributes:strAttributes];
	return rtfString;
}

@end
